let app = getApp();
const extConfig =  app.siteInfo;
const isCompanyCloudTemplate = Number(extConfig.isCloudTemplate) === 1 ? false : false;
const regeneratorRuntime = require('../../../common/vendor/runtime.js');

Component({
  properties: {
    isVirtualTabBar: {
      type: Boolean,
      value: false,
    },
    moduleIndex: {
      type: Number,
      value: 0,
    },
    isCoverView:{
      type: Boolean,
      value: true
    },
    tabData: {
      type: Array,
      value: [],
    },
    tabBar: {
      type: Object,
      value: '',
    },
    tabIndex: {
      type: Number,
      value: 0,
    },
    selectedColor: {
      type: String,
      value: '',
    },
    v_list: {
      type: Object,
      value: '',
    },
    color: {
      type: String,
      value: '',
    },
  },
  data: {
    isCompanyCloudTemplate,
    borderStyle: 'black',
  },
  methods: {
    // 响应tab点击
    _onTabbar(e) {
      let tabData = this.data.tabBarItems;
      let { index: tabIndex, type: pageType } = e.currentTarget.dataset;
      const module = app.siteInfo.module;

      if (pageType === '2') {
        this.navigateToMiniProgram(tabData[tabIndex]);
      }
      // 避免虚拟菜单重复点击造成页面刷新；
      const currentPage = getCurrentPages()[0].route;
      let url = tabData[tabIndex].pagePath;

      // 虚拟菜单
      if (pageType) {
        // 当前页面不需要跳转
        if (currentPage === tabData[tabIndex].pagePath) return;
        if (pageType === '4' && currentPage === tabData[tabIndex].realPath) return;

        if (pageType === '3') {
          // webview 跳转, 采用 wx.navigateTo 否则无法返回
          const webPageUrl = isCompanyCloudTemplate ? `${module}/pages/web/web` : app.siteInfo.appJson[0].webPage;
          wx.navigateTo({ url: `/${webPageUrl}?url=${encodeURIComponent(url)}&webview_url=${encodeURIComponent(url)}` });
          return;
        }
      } else {
        // 主模块虚拟菜单，分包菜单的跳转
        pageType = tabData[tabIndex].pageType;
        if (currentPage === url) return;
      }
      if (url[0] !== '/') {
        url = `/${url}`;
      }
      wx.reLaunch({ url });
    },

    /**
     * 单模块
     * 获取当前config中pagePath数组, 即页面路径（不带参数）
     */
    _getPagePathArray(list) {
      let pagePathArray = [];
      list.forEach(e => {
        if (e.pagePath) {
          if (e.pageType === '4' && e.pagePath.indexOf('?') !== -1) {
            pagePathArray.push(e.pagePath.substring(0, e.pagePath.indexOf('?')));
          } else {
            pagePathArray.push(e.pagePath);
          }
        }
      });
      return pagePathArray;
    },

    _getCurrentPage() {
      let pages = getCurrentPages();    // 获取加载的页面
      let currentPage = pages[pages.length - 1];    // 获取当前页面的对象
      let currentPagePath = currentPage.route;    // 当前页面currentPagePath
      return currentPagePath;
    },

    /**
     * 获取当前 tabbar 配置所在模块包索引位置
     * @returns
     * 1. 当前页面是 common 页面，返回当前主/副模块 index
     * 2. 当前页面是插件分包 tabbar 页面，返回插件分包 index
     * 3. 当前页面不是插件分包非 tabbar 页面，返回当前主/副模块 index
     */
    _getCurrentModule() {
      let currentPagePath = this._getCurrentPage();    // 当前页面url
      let currentIndexOfModule = 0;

      if (isCompanyCloudTemplate) return 0;
      const module = getCurrentPages().pop().route.split('/')[0];
      if (module === 'common') {
        return app.tabbarindex;
      }
      currentIndexOfModule = app.siteInfo.appJson.findIndex(v => v.module === module);
      if (currentIndexOfModule > -1) {
        const tabBar = app.siteInfo.appJson[currentIndexOfModule].tabBar;
        const list = tabBar.v_list || tabBar.list;
        if (list.findIndex(v => v.pagePath === currentPagePath) > -1) {
          return currentIndexOfModule;
        }
      }
      return app.tabbarindex;
    },

    _getCompanyTabBar() {
      return new Promise((resolve, reject) => {
        if (!isCompanyCloudTemplate) {  // 其他模块不支持该方法
          resolve({});
          return;
        }
        app.util.request({
          url: 'entry/wxapp/api',
          data: {
            type: 16,
          },
          cachetime: '30',
          success: res => {
            console.log(`tabbar _getCompanyTabBar success`, res);
            if (!res.data.data || !res.data.data.tabbar) {
              resolve({});  // 后台返回错误或当前模块不支持该方法
              return;
            }
            resolve(res.data.data.tabbar);
          },
          fail: res => {
            console.log(`tabbar _getCompanyTabBar fail`, res);
            reject(res);
          },
        });
      });
    },

    /**
     * 加载菜单，每个页面
     */
    async _initTabbar() {
      let modules = app.siteInfo.appJson;           // 所有的包
      let moduleIndex = this._getCurrentModule();
      let currentModule = modules[moduleIndex];            // 当前 tabBar 配置所在模块
      let currentPagePath = this._getCurrentPage(); // 当前页面路径
      let { tabBar: { color, selectedColor, list, backgroundColor }} = currentModule;
      const borderStyle = currentModule.tabBar.borderStyle || 'black';
      let isTabBarPage = false;
      let isVirtualTabBar = (moduleIndex > 0 && list.length >= 2) || isCompanyCloudTemplate || Number(app.siteInfo.tabbar_type) === 2;
      const m = modules[app.tabbarindex].module;
      list = currentModule.tabBar.v_list || currentModule.tabBar.list;
      if (isVirtualTabBar) {
        let pagePathArray = [];
        try {
          pagePathArray = this._getPagePathArray(list);
        } catch (error) {
          console.error(`tabbar _initTabbar pagePathArray error`, error);
        }
        isTabBarPage = pagePathArray.indexOf(currentPagePath) !== -1;
      }

      if (isCompanyCloudTemplate) {
        let companyTabBar;
        try {
          companyTabBar = await this._getCompanyTabBar();
        } catch (error) {
          console.error(`tabbar _initTabbar companyTabBar error`, error);
        }
        if (companyTabBar && !companyTabBar.v_list.length) return;

        list = companyTabBar.v_list;
        color = companyTabBar.color;
        selectedColor = companyTabBar.selectedColor;
        backgroundColor = companyTabBar.backgroundColor;
      }
      this.setData({
        isShowTabbar: isVirtualTabBar&&isTabBarPage ? true : false,
        m,
        tabBarItems: list,
        currentPagePath,
        color,
        selectedColor,
        borderStyle,
        backgroundColor: backgroundColor || '#fff',
      });
    },

    navigateToMiniProgram(tab) {
      let { appid = '', pagePath = '', extraData = {}} = tab;
      wx.navigateToMiniProgram({
        appId: appid,
        path: pagePath,
        extraData,
      });
    },

  },

  attached() {
    this._initTabbar();
  },
});
